package com.learn.netty.bio.single;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

/**
 * BIOServer
 *
 * <li>每个处理（读，写）必须在一个线程： read 和 write 都是 blocking 的</li>
 *
 * <ul>可扩展的目标
 * <li>更多的客户端连接</li>
 * <li>随着资源(CPU、内存、磁盘、带宽)的增加而不断改进</li>
 * <li>同时满足可用性和性能目标：低延迟、满足高峰需求、可调的服务质量</li>
 * <li>分治通常是实现任何可扩展目标的最佳方法</li>
 * </ul>
 *
 * TODO accept 和 read 阻塞的原理，阻塞是否占用 CPU 资源
 */

public class BioServer {

    private static  final int PORT = 8081;

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("start accept port: " + PORT);

            while (true) { // TODO 可中断
                socket = serverSocket.accept(); // blocking
                String socketHost = socket.getInetAddress().getHostAddress();
                int socketPort = socket.getPort();
                System.out.println("handler socket: " + socketHost + ":" + socketPort);

                inputStream = socket.getInputStream();
                byte[] buffer = new byte[1024];
                while (inputStream.read(buffer) > -1) { // blocking
                    System.out.println("recv: " + new String(buffer));

                    outputStream = socket.getOutputStream();
                    outputStream.write("seccess".getBytes()); // blocking
                    System.out.println("send msg to " + socketHost + ":" + socketPort);
                }
                System.out.println("close socket: " + socketHost + ":" + socketPort);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
                if (socket != null) socket.close();
                if (serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
